//
//  VoiceMusicCollectionViewCell.m
//  SmileRead
//
//  Created by dllo on 15/8/25.
//  Copyright (c) 2015年 JIZ. All rights reserved.
//

#import "VoiceMusicCollectionViewCell.h"
#import "Path.h"
#import "VoiceMusicModel.h"
#import <AVFoundation/AVFoundation.h>
#import "Singleton.h"
#import "MyLabel.h"
#import "AFNetworking.h"
#import "DBDataBase.h"
#import "DB.h"
#import "MyProgressView.h"


@interface VoiceMusicCollectionViewCell ()

{
    // 控制声音
    NSInteger _volume;
    // 歌曲的总时间
    float _sumOftime;
}

@property (nonatomic, retain) UIImageView *musicImage;
@property (nonatomic, retain) UILabel *titleLable;
@property (nonatomic, retain) UISlider *slider;
@property (nonatomic, retain) UIImageView *backImage;
@property (nonatomic, retain) UIVisualEffectView *effectView;
@property (nonatomic, retain) UIView *underView;
@property (nonatomic, retain) UILabel *timeLabel;

// 功能键
@property (nonatomic, retain) UIButton *playButton;
@property (nonatomic, retain) UIButton *collectButton;
@property (nonatomic, retain) UIButton *countButton;
@property (nonatomic, retain) UIButton *downlaodButton;
@property (nonatomic, retain) UIButton *backButton;
@property (nonatomic, retain) UIButton *shareButton;
// 进度条
@property (nonatomic, retain) MyProgressView *progress;
// 时间的观察者
@property (nonatomic, retain) id timeObserver;


// 用于照片的分享
@property (nonatomic, retain) UIImageView *shareImageView;

@property (nonatomic, retain) Singleton *sing;

@property (nonatomic, retain) AVPlayerLayer *playerLayer;


@end

@implementation VoiceMusicCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self createSubView];
        
    }
    return self;
}

- (void)createSubView
{
    
    // 创建分享照片
    self.shareImageView = [[UIImageView alloc] init];
    // 创建背景毛玻璃
    
    self.backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    self.backImage.userInteractionEnabled = YES;
    [self.contentView addSubview:self.backImage];
    [_backImage release];
    
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    self.effectView = [[UIVisualEffectView alloc] initWithEffect:blur];
    self.effectView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    [self.backImage addSubview:self.effectView];
    [_effectView release];
    
    
    self.contentView.backgroundColor = [UIColor whiteColor];
    
    self.musicImage = [[UIImageView alloc] initWithFrame:CGRectMake(40 * widthFit, 104 * heightFit, self.frame.size.width - 80 * widthFit, 280 * heightFit)];
    [self.contentView addSubview:self.musicImage];
    self.musicImage.backgroundColor = [UIColor cyanColor];
    [_musicImage release];
    
    self.titleLable = [[UILabel alloc] initWithFrame:CGRectMake(40 * widthFit, 384 * heightFit, self.frame.size.width - 80 * widthFit, 50 * heightFit)];
    self.titleLable.textAlignment = NSTextAlignmentCenter;
    self.titleLable.font = [UIFont systemFontOfSize:20];
    [self.contentView addSubview:self.titleLable];
    
#if 0
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(60 * widthFit, 454 * heightFit, self.frame.size.width - 120 * widthFit, 20 * heightFit)];
    [self.contentView addSubview:self.slider];
    [_slider release];
#endif
    
    // 底边
    self.underView = [[UIView alloc] initWithFrame:CGRectMake(0, self.contentView.frame.size.height - 64 * heightFit, self.contentView.frame.size.width, 64 * heightFit)];
    self.underView.backgroundColor = [UIColor whiteColor];
    [self.effectView.contentView addSubview:self.underView];
    [_underView release];
    
    
    self.playButton = [[UIButton alloc] initWithFrame:CGRectMake( self.frame.size.width / 2 - 20 * widthFit, 7 * heightFit, 40 * widthFit, 40 * widthFit)];
    [self.playButton setBackgroundImage:[UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"stop.png"]] forState:UIControlStateNormal];
    [self.playButton addTarget:self action:@selector(playMusic:) forControlEvents:UIControlEventTouchUpInside];
    [self.underView addSubview:self.playButton];
    [_playButton release];
    
    
    // 分享
    self.shareButton = [[UIButton alloc] initWithFrame:CGRectMake(80 * widthFit, 510 * heightFit, 32 * widthFit, 35 * heightFit)];
    [self.shareButton setBackgroundImage:[UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"share.png"]] forState:UIControlStateNormal];
    [self.shareButton addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
    [self.effectView.contentView addSubview:self.shareButton];
    [_shareButton release];
    
    // 搜藏
    self.collectButton = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width / 2 - 32 / 2 * widthFit, 510 * heightFit, 32 * widthFit, 35 * heightFit)];
    [self.collectButton addTarget:self action:@selector(collection:) forControlEvents:UIControlEventTouchUpInside];
    [self.effectView.contentView addSubview:self.collectButton];
    [_collectButton release];
    
    //声音
    self.countButton = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width - 112 * widthFit, 510 * heightFit, 32 * widthFit, 35 * heightFit)];
    [self.countButton setBackgroundImage:[UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"shouting.png"]] forState:UIControlStateNormal];
    [self.countButton addTarget:self action:@selector(voiceClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.effectView.contentView addSubview:self.countButton];
    [_countButton release];
    
    // 播放时间
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width - 90 * widthFit, 440 * heightFit, 60 * widthFit, 20 * heightFit)];
    //self.timeLabel.backgroundColor = [UIColor cyanColor];
    [self.effectView.contentView addSubview:self.timeLabel];
    [_timeLabel release];
    
    
    // 进度条
    self.progress = [[MyProgressView alloc] initWithFrame:CGRectMake(60 * widthFit, 464 * heightFit, self.contentView.frame.size.width - 120 * widthFit, 3 * heightFit)];
    self.progress.layer.cornerRadius = 3;
    self.progress.layer.masksToBounds = YES;
    self.progress.backgroundColor = [UIColor whiteColor];
    [self.effectView.contentView addSubview:self.progress];
    [_progress release];
    
    self.backButton = [[UIButton alloc] initWithFrame:CGRectMake(15 * widthFit, 25 * heightFit, 40 * heightFit, 40 * heightFit)];
    [self.backButton setBackgroundImage:[UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"back.png"]] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.effectView.contentView addSubview:self.backButton];
    [_backButton release];
    
}


// 点击返回
- (void)backButton:(UIButton *)button
{
    // 在推出界面是将观察者删除
    [self.sing.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [self.sing.player removeTimeObserver:self.timeObserver];
    [self.targetOfback performSelector:self.actionOfback withObject:button];
}


- (void)createPlayer
{
    // 创建的单例
    self.sing = [Singleton defaultSingleton];
    
    NSURL *songUrl = [NSURL URLWithString:_model.musicUrl];
    AVURLAsset *movieAsset = [[AVURLAsset alloc]initWithURL:songUrl options:nil];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    [self.sing.player replaceCurrentItemWithPlayerItem:playerItem];
    // 默认声音
    self.sing.player.volume = 0.5;
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.sing.player];
    self.playerLayer.frame = self.contentView.layer.bounds;
    
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    [self.contentView.layer addSublayer:self.playerLayer];
    
    [movieAsset release];
    [self.sing.player play];
    // 允许切换到外部播放模式(外音)
    [self.sing.player setAllowsExternalPlayback:YES];
    
      // 更新进度条
    [self musicProgress];
}

// 观察者方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    AVPlayerItem *item=object;
    float alltime = CMTimeGetSeconds([item duration]);
    if([keyPath isEqualToString:@"loadedTimeRanges"])
    {
        NSArray *array=item.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];
        //本次缓冲时间范围
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        
#warning 注意: 在代码中不能除以0, 若除以0, 程序会崩溃
        //缓冲总长度
        if (alltime > 0 && startSeconds > 0 && durationSeconds > 0) {
            float totalBuffer = startSeconds + durationSeconds;        self.progress.progressOfUp = (self.contentView.frame.size.width - 120 * widthFit) / alltime * totalBuffer;
        }
    }
}

// 播放进度
- (void)musicProgress
{
    AVPlayerItem *item = self.sing.player.currentItem;
    // 1秒监听一次
    self.timeObserver = [self.sing.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        // 当前播放时间
        float current = CMTimeGetSeconds(time);
        self.timeLabel.text = [self calculateWithTime:current];
        //NSLog(@"播放时间...%@", currenttime);
        // 音乐总时间
        float alltime = CMTimeGetSeconds([item duration]);
        
#warning 注意: 在代码中不能除以0, 若除以0, 程序会崩溃
        if (current > 0 && alltime > 0) {
            self.progress.progressOfOn = (self.contentView.frame.size.width - 120 * widthFit) / alltime * current;
        }
    }];
}


#warning 时间的计算
- (NSString *)calculateWithTime:(float)time
{
    NSInteger minute = time / 60;
    NSInteger seconds = time - minute * 60;
    NSString *currentTime = [NSString stringWithFormat:@"%ld:%ld", minute, seconds];
    return currentTime;
}




// 收藏事件
- (void)collection:(UIButton *)button
{
    // 点击进行收藏
    BOOL status = [DBDataBase insertWithmodel:self.model];
    if (status == YES) {
        [self.collectButton setBackgroundImage:[UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"collected.png"]] forState:UIControlStateNormal];
    }
    else {
        
        [self.collectButton setBackgroundImage:[UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"collect.png"]] forState:UIControlStateNormal];
        // 从数据库中删除
        [DBDataBase deleteWith:self.model];
    }
}

// 声音, 增大
- (void)voiceClicked:(UIButton *)button
{
    self.sing.player.volume += 0.1;
    _volume = self.sing.player.volume;
    if (_volume == 2) {
        self.sing.player.volume = 0;
    }
}

// 点击分享
- (void)share:(UIButton *)button
{
    [self.targetOfshare performSelector:self.actionOfshare withObject:self.shareImageView];
}

// 控制播放器
- (void)playMusic:(UIButton *)button
{
    
#if 1
    if (button.selected == YES) {
        [button setBackgroundImage:[UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"start.png"]] forState:UIControlStateNormal];
        [self.sing.player pause];
        
    }
    else {
        [button setBackgroundImage:[UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"stop.png"]] forState:UIControlStateNormal];
        [self.sing.player play];
    }
    button.selected = !button.selected;
#endif
    
}

- (void)setModel:(VoiceMusicModel *)model
{
    if (_model != model) {
        [_model release];
        _model = [model retain];
        
        // 确定收藏状态
        VoiceMusicModel *model = [DBDataBase selectWithId:_model.tingid];
        if (model) {
            [self.collectButton setBackgroundImage:[UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"collected.png"]] forState:UIControlStateNormal];
        }
        else {
            [self.collectButton setBackgroundImage:[UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"collect.png"]] forState:UIControlStateNormal];
        }
        
        self.titleLable.text = _model.title;
        [Path pathWithImageView:self.musicImage URLString:_model.coverimg];
        [Path pathWithImageView:self.backImage URLString:_model.coverimg];
        
        [Path pathWithImageView:self.shareImageView URLString:_model.coverimg];
        
        [self createPlayer];
        NSURL *songUrl = [NSURL URLWithString:_model.musicUrl];
        AVURLAsset *movieAsset = [[AVURLAsset alloc]initWithURL:songUrl options:nil];
        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
        [self.sing.player replaceCurrentItemWithPlayerItem:playerItem];
        [self.sing.player play];
        
        // 缓冲配置
        // 添加观察者
        [self.sing.player.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
        
    }
}

- (void)dealloc
{
    [_timeLabel release];
    [_progress release];
    [_shareImageView release];
    [_backButton release];
    [_downlaodButton release];
    [_collectButton release];
    [_countButton release];
    [_underView release];
    [_backImage release];
    [_effectView release];
    [_sing release];
    [_slider release];
    [_titleLable release];
    [_musicImage release];
    [super dealloc];
}


@end




